/*
 * 通用的数据库操作方法
        //https://github.com/dresende/node-orm2

 */
module.exports = {
    get: function(req, res) {
        var tablename = req.params.tablename;
        // console.log(req.params, req.models);
        console.log("查询表“", tablename, "”的数据", req.body, req.query);
        var finner = req.models[tablename].find({});
        require("../../include/RESTful_query").orm_get(finner, req.query);

        finner.run(function(err, result) {
            if (err) {
                res.send(500, err);
            } else {
                res.send(result);
            }
        });
    },
    post: function(req, res) {
        var tablename = req.params.tablename;
        console.log("为表“", tablename, "”添加新的元素：", req.body, req.query);
        req.models[tablename].create(req.body, function(err, result) {
            if (err) {
                res.send(500, err);
            } else {
                res.send(result);
            }
        });
    },
    put: function(req, res) {
        var tablename = req.params.tablename;
        var id = req.params.id;
        console.log("为表“", tablename, "”进行修改：", req.body, req.query);
        req.models[tablename].get(id, function(err, result) {
            if (err) {
                res.send(500, err);
            } else {
                for (var key in result) {
                    result[key] = req.body[key];
                };
                result.save(function(err) {
                    if (err) {
                        res.send(500, err);
                    } else {
                        res.send(result);
                    }
                });
            }
        });
    },
    delete: function(req, res) {
        var tablename = req.params.tablename;
        var id = req.params.id;
        req.models[tablename].get(id, function(err, result) {
            if (err) {
                res.send(500, err);
            } else {
                for (var key in result) {
                    result[key] = req.body[key];
                };
                result.remove(function(err) {
                    if (err) {
                        res.send(500, err);
                    } else {
                        // res.send(result);
                        //返回新的数据列表
                        module.exports.get(req, res)
                    }
                });
            }
        });
    },
};
